<!--
@Description:来电弹屏
@Last Modified by:zqy
@Last Modified time:2022-07-06 01:09:55
-->
<template>
  <DisplayWrap v-if="show" ref="displayWrap" :relevance="$isClient()" :call-tel="callTel" :call-id="callid" :record-id="recordId" :ivr="ivr" @refresh="updateComponentData" @inputName="inputNameHandle" @onRelevance="relevanceNameTel">
    <Client v-if="$isClient() || $isShop()||$isCustomerCare()" ref="client" :call-tel="callTel" :call-id="callid" :record-id="recordId" :customer-name="customerName"></Client>
    <Finance v-if="$isFinance()" :call-tel="callTel" :call-id="callid" :record-id="recordId" :customer-name="customerName" @refresh="updateComponentData"></Finance>
    <Sale v-if="$isSale()" :call-tel="callTel" :call-id="callid" :record-id="recordId" @refresh="updateComponentData"></Sale>
    <!-- <Shop v-if="$isShop()||$isCustomerCare()" :call-tel="callTel" :call-id="callid" :record-id="recordId" @refresh="updateComponentData"></Shop> -->
  </DisplayWrap>
</template>
<script>
import DisplayWrap from './components/DisplayWrap'
import Client from './components/Client'
import Finance from './components/Finance'
import Sale from './components/Sale'
// import Shop from './components/Shop'
import { mapGetters, mapActions, mapMutations } from 'vuex'
import { postCreate } from '@/api/telRecord'
export default {
  name: 'Display',
  components: {
    DisplayWrap,
    Client,
    Finance,
    Sale
    // Shop
  },
  provide() {
    return {
      closePage: this.$closePage,
      checkClosePage: this.checkClosePage,
      createdTelRecordHandle: this.createdTelRecordHandle
    }
  },
  data() {
    return {
      customerName: '', // 坐席输入的姓名
      callid: undefined, // 华为话务平台通话id
      callTel: undefined,
      // OnStopRecordSuccess: 'OnCallRelease', // 停止录音事件名称
      show: false,
      isSaveName: false, // 是否保存用户信息
      isSaveOther: false // 是否完成其他操作
    }
  },
  computed: {
    ...mapGetters(['user', 'agentState', 'recordList', 'agentid', 'staffName', 'firstDept']),
    ivr() {
      const callData = this.callInfo.callData || {}
      return callData.zrcdbh
    },
    callInfo() {
      return this.recordList[this.callid] || {}
    },
    recordId() {
      return this.callInfo.recordId
    }
  },
  watch: {
  },
  activated() {
    this.displayCheck()
  },
  methods: {
    ...mapActions(['updateVisitedView']),
    ...mapMutations(['SET_RECORD_LIST', 'SET_CALL_ID', 'SET_CALL_TEL']),
    // 检查能否关闭界面
    checkClosePage({ isSaveName, isSaveOther, to }) {
      if (isSaveName !== undefined) {
        this.isSaveName = isSaveName
      }
      if (isSaveOther !== undefined) {
        this.isSaveOther = isSaveOther
      }
      if (this.isSaveOther && this.isSaveName) {
        this.$closePage()
      }
    },
    // 创建通话记录
    createCallRecord() {
      const data = {
        callSerialNumber: this.callid,
        customerPhone: this.callTel,
        callType: 1, // 呼叫类型 1:呼入，2：普通呼出，3：未接呼出，4：外呼任务呼出，5：呼入转接 0：全部
        caller: this.agentid,
        callerName: this.staffName,
        department: this.firstDept,
        talkTime: 0,
        transfer: 0, // 转接类型 0未转接，1转出方，2转入方
        evaluateType: 0,
        callSource: this.$getCallSource() // 通话来源
      }
      // 判断是否是转移过来的电话
      if (this.callInfo.transferId) {
        data.transferId = this.callInfo.transferId
        data.transfer = 2
      }
      const callData = this.callInfo.callData
      if (callData) {
        data.ivrOption = callData.zrcdbh || null
        data.localNumber = callData.called || '' // 呼入被叫号码
      }
      return postCreate(data)
        .then((res) => {
          this.SET_RECORD_LIST({
            callid: this.callid,
            recordId: res.data.id
          })
          return res.data.id
        })
    },
    // 刷新数据,只要子组件有inidData方法就调用
    refreshHandle(children) {
      for (const c of children) {
        if (c.$children.length > 0) {
          this.refreshHandle(c.$children)
        }
        if (c.initData instanceof Function) {
          c.initData()
        }
      }
    },
    // 当保存时只更新通话记录
    updateTelRecord(children) {
      for (const c of children) {
        if (c.$children.length > 0) {
          this.updateTelRecord(c.$children)
        }
        if (c.updateData instanceof Function) {
          c.updateData()
        }
      }
    },
    // updateComponentData
    updateComponentData(v) {
      if (v === 'save') {
        this.updateTelRecord(this.$children)
      } else {
        this.refreshHandle(this.$children)
      }
    },
    // 根据通话callid获取随路数据  FIXME:失败！服务器异常，暂时不用
    // getCallData() {
    //   this.$cps.queryCallInfoByCallId(this.callid).then(res => {
    //     this.callData = res.data
    //   })
    // },
    // 接收坐席输入的客户姓名
    inputNameHandle(v) {
      this.customerName = v
    },
    // 获取随路数据
    getCallData() {
      if (!this.talk) return // 不在通话中，则不获取通话记录
      this.$cps.queryCallData().then(res => {
        const callData = res.data.calldata
        this.SET_RECORD_LIST({
          callid: this.callid,
          callData
        })
      })
    },
    // 弹屏检查
    displayCheck() {
    // 手动弹屏时
      if (!this.$route.query.callid) {
      // 尝试从store获取
        const callid = this.$store.state.callBar.callid
        const callTel = this.$store.state.callBar.callTel
        if (!callid || !callTel) {
          this.$alert('当前没有电话呼入！', '错误', { type: 'error' }).finally(() => {
            this.$closePage()
          })
          return
        } else {
          this.callid = callid
          this.callTel = callTel
          this.SET_RECORD_LIST({
            callid,
            callTel
          })

          // 如果弹屏成功后，坐席继续手动弹屏，则跳转到盖弹屏
          for (const view of this.$store.state.tagsView.visitedViews) {
            if (!view.query) {
              continue
            }
            if (view.query.callid === callid) {
              this.$closePage(this.$route, view)
              return
            }
          }
          // 没有找到则打开新的
          this.$closePage(this.$route, { name: 'Display', query: { callid, callTel }})
        }
      } else {
        this.callid = this.$route.query.callid
        this.callTel = this.$route.query.callTel
      }
      // 显示
      this.show = true
      if (!this.callInfo.callTel) {
        this.SET_RECORD_LIST({
          callid: this.callid,
          callTel: this.$route.query.callTel
        })
      }
      if (this.callid && Object.keys(this.callInfo.callData || {}).length <= 0) {
      // 获取随路数据
        this.getCallData()
      }
      // this.createdTelRecordHandle() // 没有recordId则创建通话记录
    },
    // 弹屏失败后，保存时先创建通话记录
    createdTelRecordHandle() {
      if (this.recordId) {
        // console.log(this.recordId, '通话记录已存在')
        return Promise.resolve(this.recordId)
      }
      // console.log(this.recordId, '通话记录不存在')
      return this.createCallRecord().catch(() => {
        this.$message.error('操作失败！')
        return Promise.reject()
      })
    },
    // 关联姓名电话
    relevanceNameTel() {
      this.$refs.client.reNameTel(this.customerName, this.callTel)
    }
  }
}
</script>
